package com.computergames.server.service.Implement;

import com.computergames.server.message.AbstractGameMessage;
import com.computergames.server.message.cardMessage.AbstractCardMessage;
import com.computergames.server.service.Interface.RuleDetermination;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class LandlordRuleDetermination implements RuleDetermination {
    private final static LandlordRuleDetermination INSTANCE = new LandlordRuleDetermination();

    private LandlordRuleDetermination() {
    }

    public static LandlordRuleDetermination getInstance() {
        return INSTANCE;
    }

    private final Map<String, Map<String, AtomicInteger>> LandlordCards = new ConcurrentHashMap<>();

    @Override
    public int ruleDetermination(String roomName, AbstractGameMessage content, ChannelHandlerContext ctx) {
        Map<String, AtomicInteger> playerCards = LandlordCards.computeIfAbsent(roomName, k -> new ConcurrentHashMap<>());
        String player = (String)ctx.attr(AttributeKey.valueOf("POSITION")).get();
        AtomicInteger cards = playerCards.computeIfAbsent(player, k -> new AtomicInteger());
        String landlord = (String)ctx.attr(AttributeKey.valueOf("LANDLORD")).get();
        AbstractCardMessage cardMessage = (AbstractCardMessage)content;

        cards.addAndGet(cardMessage.getCard().length);

        if(cards.get() == 17 && !player.equals(landlord)){
            return 1;
        } else if(cards.get() == 20 && player.equals(landlord)){
            return 1;
        }

        if(cards.get() < 17){
            return 0;
        } else if(cards.get() > 17 && cards.get() < 20 && player.equals(landlord)){
            return 0;
        }

        return -1;
    }
}
